#include "SocketIO.hpp"
#include "Socket.hpp"

#include <cstdio>
#include <unistd.h>

namespace se {

SocketIO::SocketIO(const Socket &socket) : _socket(socket) { }

int SocketIO::write(const char *buffer, int length) {
    int left = length;
    int ret = 0;

    // 保证所有的字节都发送完成
    while (left) {
        ret = ::write(this->_socket.getFileDescriptor(), buffer, length);
        if (ret == -1 && errno == EINTR) {
            continue;
        } else if (ret == -1) {
            ::perror("write");
        } else if (ret == 0) {
            return 0;
        } else {
            left -= ret;
        }
    }
    return length - left;
}

int SocketIO::read(char *buffer, int length) {
    int readLength = ::read(this->_socket.getFileDescriptor(), buffer, length);
    if (readLength >= 0) {
        buffer[readLength] = 0;
    }
    return readLength;
}

}  // namespace se